package com.yixia.framework.web.service;


import com.yixia.common.constant.CacheConstants;
import com.yixia.common.constant.Constants;
import com.yixia.common.core.domain.entity.SysUser;
import com.yixia.common.core.redis.RedisCache;
import com.yixia.common.exception.user.UserPasswordNotMatchException;
import com.yixia.common.exception.user.UserPasswordRetryLimitExceedException;
import com.yixia.common.utils.MessageUtils;
import com.yixia.common.utils.SecurityUtils;

import com.yixia.framework.manager.AsyncManager;
import com.yixia.framework.manager.factory.AsyncFactory;
import com.yixia.framework.security.context.AuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 * @author: 依梦
 * @Date 2023/8/5
 */
@Service
public class SysPasswordService {

    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;/*密码最大错误次数*/

    @Value(value = "${user.password.lockTime}")
    private int lockTime;/*密码超过最大错误次数后锁定时间*/


    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }


    /**
     * 验证
     * @param user
     */
    public void validate(SysUser user)
    {
        /*从安全安全上下文中获取上下文，从中获取令牌，获取用户名和密码*/
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        /*2. 从reids中获取该用户登录失败的次数*/
        Integer retryCount  = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null)
        {
            retryCount = 0;
        }
        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            // 账户已锁定
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        }
        else
        {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName)
    {
        if (redisCache.hasKey(getCacheKey(loginName)))
        {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }


}
